<template>
  <div class="video-detail-container">
    <div class="container">
      <!-- 视频详情区域 -->
      <div class="video-player-wrapper" v-if="!loading">
        <!-- 视频标题和作者信息 -->
        <div class="video-info-top">
            <div class="title-container">
              <div class="title-main">
                <h1 class="video-title"><span class="title-text">{{ currentVideo?.video_title || '' }}</span></h1>
                <div class="title-underline"></div>
              </div>
              <div class="author-section">
              <span class="author-name">{{ authorName || '未知作者' }}</span>
              <el-button 
                type="primary" 
                size="small" 
                class="follow-btn"
                @click="handleFollow"
                :disabled="!isLoggedIn || isFollowing || isOwnVideo"
              >
                {{ isFollowing ? '已关注' : '+ 关注' }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 视频播放区域 -->
        <div class="video-player">
          <video 
            :src="currentVideo?.video_addr || ''" 
            controls 
            class="video-element"
            @timeupdate="handleTimeUpdate"
          ></video>
          <!-- 弹幕容器 -->
          <div class="danmaku-container" ref="danmakuContainer"></div>
          <!-- 弹幕输入框 -->
          <div class="danmaku-input-wrapper" v-if="isLoggedIn">
            <el-input
              v-model="danmakuContent"
              placeholder="发送弹幕..."
              maxlength="50"
              show-word-limit
              suffix-icon="ChatDotRound"
              @click:suffix="sendDanmaku"
              @keyup.enter="sendDanmaku"
            />
            <el-color-picker
              v-model="danmakuColor"
              size="small"
              show-alpha
              @change="changeDanmakuColor"
            />
          </div>
        </div>

        <!-- 视频信息 -->
        <div class="video-info">
          <div class="video-meta">
            <div class="interaction-buttons">
              <el-button 
                :type="isLiked ? 'primary' : 'default'" 
                class="interaction-btn"
                @click="handleLike"
              >
                <el-icon><StarFilled /></el-icon>
                <span>{{ isLiked ? '已点赞' : '点赞' }}</span>
                <span class="count">{{ currentVideo?.like_count || 0 }}</span>
              </el-button>
              <el-button 
                :type="isCollected ? 'primary' : 'default'" 
                class="interaction-btn"
                @click="handleCollect"
              >
                <el-icon><CollectionTag /></el-icon>
                <span>{{ isCollected ? '已收藏' : '收藏' }}</span>
                <span class="count">{{ currentVideo?.collect_count || 0 }}</span>
              </el-button>
              <el-dropdown trigger="click" @command="handleCoin">
                <el-button type="default" class="interaction-btn">
                  <el-icon><Coin /></el-icon>
                  <span>投币</span>
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="1">1 硬币</el-dropdown-item>
                    <el-dropdown-item command="2">2 硬币</el-dropdown-item>
                    <el-dropdown-item command="3">3 硬币</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button type="default" class="interaction-btn" @click="handleShare">
                <el-icon><Share /></el-icon>
                <span>分享</span>
              </el-button>
            </div>
          </div>
          <div class="video-intro">
            <h3>视频简介</h3>
            <p>{{ currentVideo?.video_desc || '' }}</p>
            <div class="video-stats">
              <span><el-icon><View /></el-icon> 播放 {{ currentVideo?.view_count || 0 }}</span>
              <span><el-icon><Calendar /></el-icon> 发布于 {{ formatDate(currentVideo?.video_time) }}</span>
            </div>
          </div>
        </div>

        <!-- 评论区 -->
        <div class="comment-section">
          <h2>评论 ({{ comments.total }})</h2>
          <!-- 评论输入 -->
          <div class="comment-input-wrapper" v-if="isLoggedIn">
            <el-avatar :size="48" :src="userAvatar">{{ currentUser?.username?.[0] }}</el-avatar>
            <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="发表你的评论..."
              maxlength="500"
              show-word-limit
            />
            <el-button type="primary" @click="submitComment" :disabled="!commentContent.trim()">
              发布评论
            </el-button>
          </div>
          <div v-else class="login-prompt">
            请先 <router-link to="/login">登录</router-link> 后发表评论
          </div>
          
          <!-- 评论列表 -->
          <div class="comment-list">
            <div v-for="comment in comments.comments" :key="comment.comment_id" class="comment-item">
              <el-avatar :size="40" :src="getUserAvatar(comment.user_id)">{{ getUserName(comment.user_id)?.[0] }}</el-avatar>
              <div class="comment-content">
                <div class="comment-header">
                  <span class="comment-username">{{ getUserName(comment.user_id) }}</span>
                  <span class="comment-time">{{ formatTime(comment.comment_time) }}</span>
                </div>
                <p class="comment-text">{{ comment.content }}</p>
                <div class="comment-actions">
                  <el-button type="text" size="small">
                    <el-icon><ChatDotRound /></el-icon>
                    回复
                  </el-button>
                  <el-button type="text" size="small">
                    <el-icon><StarFilled /></el-icon>
                    {{ comment.like_count || 0 }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <el-pagination
            v-model:current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="comments.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <el-empty v-else description="加载中..." class="loading-container" />

      <!-- 右侧推荐 -->
      <div class="recommendation-sidebar">
        <h3>相关推荐</h3>
        <div class="recommendation-list">
          <div 
            v-for="video in relatedVideos" 
            :key="video.video_id"
            class="recommendation-item"
            @click="goToVideoDetail(video.video_id)"
          >
            <img 
              :src="video.video_cover || '/placeholder.svg?size=150x84'" 
              :alt="video.video_title"
              class="recommendation-cover"
            >
            <div class="recommendation-info">
              <h4 class="recommendation-title">{{ video.video_title }}</h4>
              <div class="recommendation-meta">
                <span>{{ getUserName(video.user_id) }}</span>
                <span>{{ video.view_count }} 播放</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useVideoStore } from '../store/videoStore'
import { useUserStore } from '../store/userStore'
import { StarFilled, CollectionTag, Coin, Share, View, Calendar, ChatDotRound, ArrowDown } from '@element-plus/icons-vue'
import { ElButton, ElAvatar, ElDropdown, ElDropdownMenu, ElDropdownItem, ElInput, ElColorPicker, ElEmpty, ElPagination } from 'element-plus'
import { ElMessage } from 'element-plus'

export default {
  name: 'VideoDetailView',
  components: {
    ElButton,
    ElAvatar,
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
    ElInput,
    ElColorPicker,
    ElEmpty,
    ElPagination,
    StarFilled,
    CollectionTag,
    Coin,
    Share,
    View,
    Calendar,

    ChatDotRound,
    ArrowDown
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const videoStore = useVideoStore()
    const userStore = useUserStore()
    const danmakuContainer = ref(null)
    
    const commentContent = ref('')
    const danmakuContent = ref('')
    const danmakuColor = ref('#ffffff')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const isLiked = ref(false)
    const isCollected = ref(false)
    const comments = ref({ comments: [], total: 0 })
    const relatedVideos = ref([])
    const currentTime = ref(0)

    onMounted(async () => {
      await initPage()
    })

    watch(() => route.params.id, async () => {
      await initPage()
    })

    const initPage = async () => {
      const videoId = parseInt(route.params.id)
      if (!isNaN(videoId)) {
        await Promise.all([
          videoStore.fetchVideoById(videoId),
          loadComments(videoId, currentPage.value, pageSize.value),
          loadRelatedVideos(videoId),
          checkUserInteractions(videoId)
        ])
      }
    }

    const loadComments = async (videoId, page, size) => {
      try {
        const result = await videoStore.fetchVideoComments(videoId, page, size)
        comments.value = result
      } catch (error) {
        console.error('加载评论失败:', error)
      }
    }

    const loadRelatedVideos = async (videoId) => {
      try {
        relatedVideos.value = await videoStore.fetchRelatedVideos(videoId, 10)
      } catch (error) {
        console.error('加载相关视频失败:', error)
      }
    }

    const checkUserInteractions = async (videoId) => {
      if (!userStore.isLoggedIn) return
      
      try {
        // 检查是否点赞
        const likes = await userStore.getMyLikes()
        isLiked.value = likes.some(like => like.video_id === videoId)
        
        // 检查是否收藏
        const collections = await userStore.getMyCollections()
        isCollected.value = collections.some(collection => collection.video_id === videoId)
      } catch (error) {
        console.error('检查用户交互状态失败:', error)
      }
    }

    const handleTimeUpdate = (event) => {
      currentTime.value = event.target.currentTime
      // 显示当前时间的弹幕
      showDanmakusAtTime(currentTime.value)
    }

    const showDanmakusAtTime = (time) => {
      // 简化实现，实际应该有更复杂的弹幕管理逻辑
      if (!danmakuContainer.value) return
      
      // 这里可以根据时间筛选并显示弹幕
    }

    const sendDanmaku = async () => {
      if (!danmakuContent.value.trim()) return
      
      if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        return
      }
      
      try {
        const result = await videoStore.addDanmaku(
          currentVideo.value.video_id,
          danmakuContent.value.trim(),
          danmakuColor.value,
          currentTime.value
        )
        
        if (result.success) {
          // 立即显示发送的弹幕
          showNewDanmaku(result.danmaku)
          danmakuContent.value = ''
        }
      } catch (error) {
        console.error('发送弹幕失败:', error)
      }
    }

    const showNewDanmaku = (danmaku) => {
      if (!danmakuContainer.value) return
      
      const danmakuElement = document.createElement('div')
      danmakuElement.className = 'danmaku-item'
      danmakuElement.style.color = danmaku.color
      danmakuElement.textContent = danmaku.content
      
      // 随机垂直位置
      const top = Math.random() * (danmakuContainer.value.clientHeight - 30) + 'px'
      danmakuElement.style.top = top
      
      danmakuContainer.value.appendChild(danmakuElement)
      
      // 弹幕动画结束后移除
      setTimeout(() => {
        danmakuElement.remove()
      }, 8000)
    }

    const changeDanmakuColor = (color) => {
      danmakuColor.value = color
    }

    const submitComment = async () => {
      if (!commentContent.value.trim()) return
      
      if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        return
      }
      
      try {
        const result = await videoStore.addComment(
          currentVideo.value.video_id,
          commentContent.value
        )
        
        if (result.success) {
          commentContent.value = ''
          // 重新加载评论
          await loadComments(currentVideo.value.video_id, 1, pageSize.value)
          ElMessage.success('评论成功')
        } else {
          ElMessage.error(result.message || '评论失败')
        }
      } catch (error) {
        console.error('提交评论失败:', error)
        ElMessage.error('评论失败')
      }
    }

    const handleLike = async () => {
      if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        return
      }
      const result = await userStore.likeVideo(currentVideo.value.video_id)
      if (result.success) {
        isLiked.value = result.liked ?? !isLiked.value
      }
    }

    const handleCollect = async () => {
      if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        return
      }
      const result = await userStore.collectVideo(currentVideo.value.video_id)
      if (result.success) {
        isCollected.value = result.collected ?? !isCollected.value
      }
    }

    const handleCoin = async (coinValue = 1) => {
      if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        return
      }
      const result = await userStore.coinVideo(currentVideo.value.video_id, parseInt(coinValue))
      if (result.success) {
        // 更新投币数
        videoStore.currentVideo.coin_count += parseInt(coinValue)
        // 显示成功提示
      } else if (result.message) {
        ElMessage.warning(result.message)
      }
    }

    const handleShare = () => {
      // 分享功能实现
      const url = window.location.href
      navigator.clipboard.writeText(url).then(() => {
        // 显示复制成功提示
      })
    }

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      loadComments(currentVideo.value.video_id, currentPage.value, newSize)
    }

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      loadComments(currentVideo.value.video_id, newPage, pageSize.value)
    }

    const goToVideoDetail = (videoId) => {
      router.push(`/video/${videoId}`)
    }

    const formatDate = (dateString) => {
      if (!dateString) return ''
      return new Date(dateString).toLocaleDateString('zh-CN')
    }


    
    const formatTime = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      } else if (diff < 604800000) {
        return Math.floor(diff / 86400000) + '天前'
      } else {
        return date.toLocaleDateString('zh-CN')
      }
    }

    const getUserName = (userId) => {
      const userMap = {
        1: '张三',
        2: '李四',
        3: '王五',
        4: '赵六',
        5: '测试用户1',
        6: '测试用户2'
      }
      return userMap[userId] || '未知用户'
    }

    const getUserAvatar = (userId) => {
      const avatarColors = ['#f56c6c', '#e6a23c', '#5cb87a', '#1989fa', '#6f7ad3', '#909399']
      return avatarColors[(userId - 1) % avatarColors.length]
    }

    // 计算属性
    const currentVideo = computed(() => videoStore.currentVideo)
    const loading = computed(() => videoStore.loading)
    const isLoggedIn = computed(() => userStore.isLoggedIn)
    const currentUser = computed(() => userStore.currentUser)
    const authorName = computed(() => getUserName(currentVideo.value?.user_id))
    const authorAvatar = computed(() => getUserAvatar(currentVideo.value?.user_id))
    const userAvatar = computed(() => {
      if (!currentUser.value) return ''
      const avatarColors = ['#f56c6c', '#e6a23c', '#5cb87a', '#1989fa', '#6f7ad3', '#909399']
      return avatarColors[(currentUser.value.user_id - 1) % avatarColors.length]
    })
    
    // 关注作者
    const isFollowing = ref(false)
    const isOwnVideo = computed(() => {
      return userStore.isLoggedIn && currentVideo.value?.user_id === userStore.currentUser?.user_id
    })
    
    const handleFollow = async () => {
      if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        return
      }
      
      // 检查是否是自己的视频
      if (isOwnVideo.value) {
        ElMessage.warning('不能关注自己')
        return
      }
      
      const result = await userStore.followUser(currentVideo.value.user_id)
      if (result.success) {
        isFollowing.value = result.following ?? !isFollowing.value
      } else if (result.message) {
        ElMessage.warning(result.message)
      }
    }
    
    // 检查当前用户是否已关注该作者
    const checkFollowingStatus = async () => {
      if (!userStore.isLoggedIn || !currentVideo.value?.user_id) return
      
      const result = await userStore.isFollowing(currentVideo.value.user_id)
      isFollowing.value = result.following
    }
    
    // 监听视频变化，检查关注状态
    watch(() => currentVideo.value, () => {
      if (currentVideo.value?.user_id) {
        checkFollowingStatus()
      }
    }, { immediate: true })

    return {
      currentVideo,
      loading,
      comments,
      relatedVideos,
      commentContent,
      danmakuContent,
      danmakuColor,
      currentPage,
      pageSize,
      isLiked,
      isCollected,
      isLoggedIn,
      currentUser,
      authorName,
      authorAvatar,
      userAvatar,
      danmakuContainer,
      isFollowing,
      isOwnVideo,
      handleFollow,
      submitComment,
      sendDanmaku,
      changeDanmakuColor,
      handleTimeUpdate,
      handleLike,
      handleCollect,
      handleCoin,
      handleShare,
      handleSizeChange,
      handleCurrentChange,
      goToVideoDetail,
      formatDate,
      formatTime,
      getUserName,
      getUserAvatar
    }
  }
}
</script>

<style scoped>
.video-detail-container {
  background: var(--bg-primary);
  min-height: calc(100vh - 60px);
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  gap: 20px;
}

.video-player-wrapper {
  flex: 1;
  background: var(--bg-card);
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid var(--border-color);
}

.video-player {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 宽高比 */
  background: #000;
}

.video-element {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.danmaku-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.danmaku-item {
  position: absolute;
  white-space: nowrap;
  font-size: 16px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
  animation: danmakuMove 8s linear;
  left: 100%;
}

@keyframes danmakuMove {
  from { transform: translateX(0); }
  to { transform: translateX(-100%); }
}

.danmaku-input-wrapper {
  position: absolute;
  bottom: 10px;
  left: 10px;
  right: 100px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.video-info {
  padding: 20px;
  border-bottom: 1px solid var(--border-color);
}

.video-info-top {
  padding: 15px 0 10px;
  margin-bottom: 10px;
}

.title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.video-title {
  margin: 0;
  font-size: 22px;
  color: var(--text-primary);
  font-weight: 600;
}

.video-title .title-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.author-section {
  display: flex;
  align-items: center;
  gap: 10px;
  white-space: nowrap;
  margin-left: 20px;
}

.title-main {
  flex: 1;
  min-width: 0;
}

.title-underline {
  width: 100%;
  height: 3px;
  background-color: #1677ff;
  margin-top: 8px;
}

.author-name {
  font-size: 14px;
  color: var(--text-secondary);
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.author-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.author-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
}

.follow-btn {
  align-self: flex-start;
}

.interaction-buttons {
  display: flex;
  gap: 15px;
}

.interaction-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.interaction-btn .count {
  font-size: 12px;
  color: var(--text-secondary);
}

.video-intro {
  margin-top: 20px;
}

.video-intro h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: var(--text-primary);
}

.video-intro p {
  margin: 0 0 15px 0;
  line-height: 1.6;
  color: var(--text-secondary);
}

.video-stats {
  display: flex;
  gap: 30px;
  font-size: 14px;
  color: var(--text-disabled);
}

.video-stats span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.comment-section {
  padding: 20px;
}

.comment-section h2 {
  margin: 0 0 20px 0;
  font-size: 20px;
  color: var(--text-primary);
}

.comment-input-wrapper {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.login-prompt {
  padding: 20px;
  background: var(--bg-secondary);
  border-radius: 4px;
  text-align: center;
  margin-bottom: 30px;
  border: 1px solid var(--border-color);
}

.comment-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  display: flex;
  gap: 15px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.comment-username {
  font-weight: 500;
  color: var(--text-primary);
}

.comment-time {
  font-size: 12px;
  color: var(--text-disabled);
}

.comment-text {
  margin: 0 0 10px 0;
  line-height: 1.6;
  color: var(--text-primary);
}

.comment-actions {
  display: flex;
  gap: 20px;
}

.recommendation-sidebar {
  width: 300px;
  flex-shrink: 0;
}

.recommendation-sidebar h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: var(--text-primary);
}

.recommendation-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.recommendation-item {
  display: flex;
  gap: 10px;
  cursor: pointer;
  background: var(--bg-card);
  padding: 10px;
  border-radius: 8px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border: 1px solid var(--border-color);
}

.recommendation-item:hover {
  transform: translateX(5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}

.recommendation-cover {
  width: 150px;
  height: 84px;
  object-fit: cover;
  border-radius: 4px;
  flex-shrink: 0;
}

.recommendation-info {
  flex: 1;
  min-width: 0;
}

.recommendation-title {
  margin: 0 0 5px 0;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.recommendation-meta {
  font-size: 12px;
  color: var(--text-disabled);
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.loading-container {
  flex: 1;
  padding: 50px 0;
  background: var(--bg-card);
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .container {
    flex-direction: column;
  }
  
  .recommendation-sidebar {
    width: 100%;
  }
  
  .danmaku-input-wrapper {
    right: 10px;
  }
}

@media (max-width: 768px) {
  .video-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }
  
  .interaction-buttons {
    width: 100%;
    justify-content: space-around;
  }
  
  .comment-input-wrapper {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .recommendation-item {
    flex-direction: column;
  }
  
  .recommendation-cover {
    width: 100%;
  }
}
</style>